package com.imooc.controller;

import com.imooc.enums.OperatorFriendRequestTypeEnum;
import com.imooc.enums.SearchFriendsStatusEnum;
import com.imooc.pojo.ChatMsg;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.userBO;
import com.imooc.pojo.vo.MyFriendsVO;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UserService;
import com.imooc.service.impl.QiNiuServiceImpl;
import com.imooc.service.impl.UserServiceImpl;
import com.imooc.service.qiniuService;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.ImageUtils;
import com.imooc.utils.MD5Utils;
import com.qiniu.http.Response;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.List;

@RestController
@RequestMapping("u")
public class UserController {

    // 不用new 的，spring 自动管理对象的额创建和删除
    @Autowired
    private UserServiceImpl userService;


    // 返回之前的json包装类
    // 该路由用于用户的注册和登陆
    @PostMapping("/registOrLogin")
    public IMoocJSONResult registOrLogin(@RequestBody Users user ) throws Exception {

        // 判断用户名和密码不能为空
        if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return IMoocJSONResult.errorMsg("用户名或密码不能为空");
        }

        Users userResult = null ;

        if(userService.queryUsernameIsExist(user.getUsername())){

            // 走登陆的逻辑
           userResult = userService.queryUserForLogin(user.getUsername(),MD5Utils.getMD5Str(user.getPassword()));

           if(userResult == null){
               return IMoocJSONResult.errorMsg("用户名或密码不正确...");
           }

        }else {

            // 走注册的逻辑

            user.setNickname(user.getUsername());
            user.setFaceImage("");
            user.setFaceImageBig("");
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));

            userResult = userService.saveUser(user);

        }

        UsersVO target = new UsersVO();

        BeanUtils.copyProperties(userResult,target);

        return IMoocJSONResult.ok(target);

    }

    @Autowired
    private QiNiuServiceImpl qiniuService ;

    /**
     * 以流的形式上传图片
     *
     * @param file value 是文件
     * @return 返回访问路径
     * @throws IOException
     */
    @Autowired
    private ImageUtils imageUtils ;

    @PostMapping("/uploadFaceBase64")
    public IMoocJSONResult uploadFile(@RequestBody userBO userBO) throws Exception {

        System.out.println("接收到上传的图片");

        // 将base64 上传

        String base64File = userBO.getFaceData();

        System.out.println(base64File);

      File file = ImageUtils.base64ToFile(base64File,"./png/"+String.valueOf(System.currentTimeMillis()) + ".png");

         String res = qiniuService.uploadFile(file);

        // 将 file 转为 inputstream
        InputStream in = new FileInputStream(file);

        // 生成缩略图
        in =  ImageUtils.thumbnailImage(in,120,120);

      file =  ImageUtils.inputstreamtofile(in,"./png/"+String.valueOf(System.currentTimeMillis()) + ".png" );

        String url = qiniuService.uploadFile(file);

        in.close();

        Users users = new Users();

        users.setId(userBO.getUserId());

        users.setFaceImageBig(res);

        users.setFaceImage(url);

        // 更新完返回更新后用户的数据
        Users result = userService.updateUserInfo(users);

        System.out.println("上传完成");

        return IMoocJSONResult.ok(result);

    }

    // 更新用户的昵称
    @PostMapping("/setNickname")
    public IMoocJSONResult setNickname(@RequestBody userBO userBO){

        System.out.println("接收到修改昵称的请求");

       // System.out.println(userBO);

        Users users = new Users();
        users.setId(userBO.getUserId());
        users.setNickname(userBO.getNickname());

       // System.out.println(users);

        Users result = userService.updateUserInfo(users);

        return IMoocJSONResult.ok(result);
    }

    // 搜索好友接口，根据账号做匹配查询
    // 搜索好友，搜的是好友的账号，传上来的是想添加的好友的账号名和用户的自己的id
    @PostMapping("/search")
    public IMoocJSONResult searchUser(String myUserId,String friendUsername){

        System.out.println("接收到"+myUserId+"搜索好友"+friendUsername+"的请求");


       if(StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)){
           return IMoocJSONResult.errorMsg("");
       }

        Integer status = userService.preconditionSearchFriends(myUserId, friendUsername);

       // 如果正确，就把查询到的用户信息返回给前端，否则就返回错误的信息
       if(status == SearchFriendsStatusEnum.SUCCESS.status){

         Users users =  userService.queryUserInfoByUsrname(friendUsername);

         UsersVO usersVO = new UsersVO();

         BeanUtils.copyProperties(users,usersVO);

         return IMoocJSONResult.ok(usersVO);

       }else{
         String errorMsg =  SearchFriendsStatusEnum.getMsgByKey(status);
         return IMoocJSONResult.errorMsg(errorMsg);
       }

    }


    // 添加好友的接口
    @PostMapping("/addFriendRequest")
    public IMoocJSONResult addFriend(String myUserId , String friendUsername){

        System.out.println("接收到"+myUserId+"添加好友"+friendUsername+"的请求");

        if(StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)){
            return IMoocJSONResult.errorMsg("");
        }


        Integer status = userService.preconditionSearchFriends(myUserId, friendUsername);

        // 如果正确，就把查询到的用户信息返回给前端，否则就返回错误的信息
        if(status == SearchFriendsStatusEnum.SUCCESS.status){

            // 发送添加好友的请求
            userService.sendFriendRequest(myUserId, friendUsername);

        }else{
            String errorMsg =  SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(errorMsg);
        }

        // 添加好友的请求成功
        return  IMoocJSONResult.ok();

    }

    // 查询好友的请求
    @PostMapping("/queryFriendRequest")
    public IMoocJSONResult queryFriendRequest( String userId){

        System.out.println("接收到"+userId+"查询好友们的添加申请");

        if(StringUtils.isBlank(userId) ){
            return IMoocJSONResult.errorMsg("");
        }

        // 查询用户接收到的朋友申请
        return IMoocJSONResult.ok(userService.queryFriendRequestList(userId));

    }

    // 接收方通过或者忽略朋友请求
    @PostMapping("/operFriendRequest")
    public IMoocJSONResult operFriendRequest( String acceptUserId, String sendUserId , Integer operType){

        System.out.println("接收到操作好友申请的请求");



        if(StringUtils.isBlank(acceptUserId) || StringUtils.isBlank(sendUserId) || operType == null){
            return IMoocJSONResult.errorMsg("");
        }


        if(StringUtils.isBlank(OperatorFriendRequestTypeEnum.getMsgByType(operType))){
            return IMoocJSONResult.errorMsg("");
        }

       if(operType == OperatorFriendRequestTypeEnum.IGNORE.type){
                userService.deleteFriendRequest(sendUserId, acceptUserId);
       }else{
                userService.addFriendRequest(sendUserId, acceptUserId);
       }

       return  IMoocJSONResult.ok();

    }

    @PostMapping("/myFriends")
    public IMoocJSONResult myFriends(String userId){

        if(StringUtils.isBlank(userId)){
            return IMoocJSONResult.errorMsg("");
        }

        // 1.数据库查询好友列表
        List<MyFriendsVO> myFriends = userService.queryMyFriend(userId);

        return IMoocJSONResult.ok(myFriends);

    }

    // 用户手机端获取未签收的消息列表
    @PostMapping("/getUnReadMsgList")
    public IMoocJSONResult getUnReadMsgList(String acceptuserId){

        if(StringUtils.isBlank(acceptuserId)){
            return IMoocJSONResult.errorMsg("");
        }

        // 1.数据库查询好友列表
        List<ChatMsg> unreadMsgList = userService.getUnReadMsgList(acceptuserId);

        return IMoocJSONResult.ok(unreadMsgList);

    }

}
